// Tierless
// Copyright © 2010 Alphora
// This file is licensed under a modified BSD-license (see tierless_license.txt).
using System;
using System.Runtime.Serialization;

using Tierless.Framework.Entities;
using Tierless.Framework.EntityTypes;

namespace Tierless.Framework.Constraints.Common
{
	/// <summary>
	/// Enforces that a pair of dates represents a valid date range.
	/// </summary>
	[DataContract]
	public class DateRangeValid : EntityConstraint
	{
		/// <summary>
		/// Constructs a new instance of a DateRangeValid constraint.
		/// </summary>
		/// <param name="entityTypeName">The name of the entity on which the constraint will be placed.</param>
		/// <param name="fromDateColumnName">The name of the from date column.</param>
		/// <param name="toDateColumnName">The name of the to date column.</param>
		public DateRangeValid(string entityTypeName, string fromDateColumnName, string toDateColumnName)
			: base
			(
				String.Format("{0}_{1}_{2}DateRangeValid", entityTypeName, fromDateColumnName, toDateColumnName),
				entityTypeName,
				new[] { fromDateColumnName, toDateColumnName },
				String.Format("{0} date must be less than or equal to {1} date.", fromDateColumnName, toDateColumnName)
			)
		{
			_fromDateColumnName = fromDateColumnName;
			_toDateColumnName = toDateColumnName;
		}

		[DataMember]
		private string _fromDateColumnName;
		/// <summary>
		/// Gets or sets the name of the from date column in the interval.
		/// </summary>
		public string FromDateColumnName
		{
			get { return _fromDateColumnName; }
			set { _fromDateColumnName = value; }
		}

		[DataMember]
		private string _toDateColumnName;
		/// <summary>
		/// Gets or sets the name of the to date column in the interval.
		/// </summary>
		public string ToDateColumnName
		{
			get { return _toDateColumnName; }
			set { _toDateColumnName = value; }
		}

		protected override bool IsValid(ConstraintContext context)
		{
			return
				context.Entity[_fromDateColumnName].IsNull
					|| context.Entity[_toDateColumnName].IsNull
						|| (context.Entity[_fromDateColumnName].AsDateTime <= context.Entity[_toDateColumnName].AsDateTime);
		}
	}
}